package com.douyinkan.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.lang.reflect.Method;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

@Configuration
@EnableAsync
public class AsyncConfig implements AsyncConfigurer {

    private static final Logger logger = LoggerFactory.getLogger(AsyncConfig.class);

    @Override
    @Bean(name = "taskExecutor")
    public Executor getAsyncExecutor() {
        logger.info("=== Creating custom thread pool executor ===");

        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        
        // 核心线程数：根据CPU核心数动态设置，但不超过10
        int corePoolSize = Math.min(10, Runtime.getRuntime().availableProcessors());
        executor.setCorePoolSize(corePoolSize);
        
        // 最大线程数：根据需要动态调整
        executor.setMaxPoolSize(200);
        
        // 队列容量：使用有界队列，避免内存溢出
        executor.setQueueCapacity(200);
        
        // 线程名称前缀
        executor.setThreadNamePrefix("MediaScan-");
        
        // 拒绝策略：当线程池和队列都满时，使用调用者线程直接执行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        
        // 线程空闲时间：60秒
        executor.setKeepAliveSeconds(60);
        
        logger.info("ThreadPool configuration - Core: {}, Max: {}, Queue: {}", 
                   corePoolSize, 50, 200);
        
        executor.initialize();
        
        logger.info("=== Custom thread pool executor created successfully ===");
        return executor;
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return new MediaAsyncExceptionHandler();
    }

    /**
     * 自定义异步任务异常处理器
     */
    private static class MediaAsyncExceptionHandler implements AsyncUncaughtExceptionHandler {
        private static final Logger logger = LoggerFactory.getLogger(MediaAsyncExceptionHandler.class);

        @Override
        public void handleUncaughtException(Throwable ex, Method method, Object... params) {
            logger.error("异步任务执行异常 - 方法: {}.{} 参数: {}", 
                        method.getDeclaringClass().getSimpleName(), 
                        method.getName(), 
                        java.util.Arrays.toString(params), ex);
        }
    }
}